"use strict";
import * as React from 'react';
import { autoSize, commonProps, commonStyles } from "../../assets/styles/common";
import Colors from "../../assets/styles/Colors";
import NavBackButton from "../../component/BackButton";
import MyText from "../../component/MyText";
import Avatar from "../../component/Avatar";
import { messageStyle } from "../../assets/styles/message";
import ContactUser from "../../component/ContactUser";
import Request from "../../utils/Request";
import constant from "../../utils/constant";
const { View, TextInput, TouchableOpacity, FlatList, DeviceEventEmitter } = require('react-native');
const NavigationBar = require('react-native-navbar').default;
const { Actions } = require("react-native-router-flux");
const { connect } = require('react-redux');
const { GiftedChat } = require('react-native-gifted-chat');
class Page extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            receiver: null,
            inputValue: null,
            messages: [],
        };
        this.onChangeText = (text) => {
            this.setState({ receiver: null });
            this.props.dispatch({
                type: 'chat/searchUser',
                payload: {
                    pi: 1,
                    ps: 40,
                    nickName: text,
                }
            });
        };
        this.onReceiverItemPress = (item) => {
            this.setState({ receiver: item });
            this.fetchMessageList(item);
        };
        this.fetchMessageList = (receiver) => {
            this.props.dispatch({
                type: 'chat/fetchMessageList',
                payload: {
                    receiver: receiver.account,
                    pi: 1,
                    ps: 20
                }
            });
            this.props.dispatch({
                type: 'message/readMessageFromUser',
                payload: {
                    receiver: receiver.account,
                }
            });
        };
        this.onLoadMore = (loadmore) => {
            if (!this.props.chat.messageList.last) {
                this.props.dispatch({
                    type: 'chat/fetchMessageList',
                    payload: {
                        receiver: this.state.receiver.account,
                        pi: this.props.chat.messageList.number + 2,
                        ps: 20,
                        loadmore: true
                    }
                });
            }
        };
        this.renderLoading = () => {
            return (<View style={[commonStyles.flex1, commonStyles.centerVH]}>
                <MyText>初始化中...</MyText>
            </View>);
        };
        this.renderTipView = () => {
            if (this.state.receiver)
                return null;
            let tip = '暂无结果';
            if (this.props.chat.searchUsers && this.props.chat.searchUsers.content.length > 0) {
                tip = `匹配到${this.props.chat.searchUsers.content.length}名会员`;
            }
            return (<View style={{ backgroundColor: Colors.Background, paddingLeft: 60, paddingVertical: 10 }}>
                <MyText color={Colors.Black} fontSize={15} fontWeight={'500'}>{tip}</MyText>
            </View>);
        };
        this.renderReceiverItem = (props) => {
            const item = props.item;
            let info = '';
            if (item.duty) {
                info += item.duty + 'at ';
            }
            if (item.company) {
                info += item.company.name;
            }
            let avatar = Request.checkImageUrl(item.avatar) + '';
            if (avatar && avatar.toLocaleLowerCase().indexOf('default-avatar.png') !== -1) {
                avatar = '';
            }
            return (<TouchableOpacity onPress={this.onReceiverItemPress.bind(this, item)}>
                <View style={[commonStyles.flexRow, messageStyle.messageContainer]}>
                    <View style={[commonStyles.centerVH]}>
                        <Avatar source={{ uri: item.avatar }} size={autoSize(65)} placeholder={require('../../assets/image/default-avatar.png')}/>
                    </View>
                    <View style={[commonStyles.flexColumn, commonStyles.flex1, messageStyle.infoContainer]}>
                        <MyText style={messageStyle.text} fontSize={15} color={Colors.Title}>{item.nickName}</MyText>
                        <MyText style={messageStyle.text} fontSize={15} color={Colors.Title} numberOfLines={1}>{info}</MyText>
                        
                    </View>
                </View>
            </TouchableOpacity>);
        };
        this.renderReceiverList = () => {
            if (this.state.receiver)
                return null;
            if (!this.props.chat.searchUsers || this.props.chat.searchUsers.content.length <= 0)
                return null;
            return (<FlatList data={this.props.chat.searchUsers.content} style={{ backgroundColor: Colors.White }} keyboardDismissMode={'on-drag'} keyExtractor={(_, index) => index} extraData={this.props.chat.searchUsers} renderItem={this.renderReceiverItem}/>);
        };
        this.renderChatView = () => {
            if (!this.state.receiver)
                return null;
            return (<View style={[commonStyles.flex1, { backgroundColor: Colors.White }]}>
                <ContactUser user={this.state.receiver}/>
                <GiftedChat messages={this.props.chat.messageList ? this.props.chat.messageList.content : []} onSend={(messages) => this.onSend(messages)} renderLoading={this.renderLoading} onLoadEarlier={this.onLoadMore} loadEarlier={true} isLoadingEarlier={this.props.chat.loading} user={{
                _id: this.props.auth.userInfo.account,
            }}/>
            </View>);
        };
        this.searchUrl = Request.getApi().searchUser;
    }
    componentDidMount() {
        this.setState({
            messages: [
                {
                    _id: 1,
                    text: 'Hello developer',
                    createdAt: new Date(),
                    user: {
                        _id: 2,
                        name: 'React Native',
                        avatar: 'https://facebook.github.io/react/img/logo_og.png',
                    },
                },
            ],
        });
    }
    onSend(messages = []) {
        DeviceEventEmitter.emit(constant.noticeKeyOfSendMessage, {
            receiver: this.state.receiver.account,
            sender: this.props.auth.userInfo.account,
            receiverId: this.state.receiver.id,
            senderId: this.props.auth.userInfo.id,
            message: messages[0],
            nickname: this.props.auth.userInfo.nickName,
            avatar: this.props.auth.userInfo.avatar || '',
        });
    }
    render() {
        return (<View style={[commonStyles.container]}>
                <NavigationBar {...commonProps.navBar} leftButton={<NavBackButton icon={{ name: 'icon-cha1', color: Colors.White, size: autoSize(24) }}/>} title={{ title: this.props.title, tintColor: '#fff' }}/>
                <View style={[commonStyles.flexRow, { alignItems: 'center', padding: 10, backgroundColor: Colors.White }]}>
                    <MyText color={Colors.SubTitle} fontSize={15}>收件人:</MyText>
                    <TextInput placeholder='输入联系人' autoFocus defaultValue={this.state.receiver ? this.state.receiver.nickName : ''} ref={ref => this.input = ref} onChangeText={this.onChangeText} style={{ fontSize: 15, display: 'flex', flex: 1 }}/>
                </View>
                {this.renderTipView()}
                {this.renderReceiverList()}
                {this.renderChatView()}
            </View>);
    }
}
export default connect(({ auth, message, chat }) => ({ auth, message, chat }))(Page);
